package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.config.R;
import com.example.dao.EmployeeDao;
import com.example.entity.Employee;
import com.example.examples.NameException;
import com.example.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;


@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeDao,Employee> implements EmployeeService{
    @Autowired
    private EmployeeDao employeeDao;

    @Override
    public R<Employee> login(Employee employee) {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee selectOne = employeeDao.selectOne(queryWrapper);
        if (selectOne==null){
            return R.error("用户不存在");
        }
//        String hex= DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        String password=employee.getPassword();
        password=DigestUtils.md5DigestAsHex(password.getBytes());
        if (!selectOne.getPassword().equals(password)){
            return R.success("登陆失败");
        }
        if (selectOne.getStatus()==0){
            return R.error("账号已被禁用");
        }
        return R.success(selectOne);

    }

    @Override
    public void add(Employee employee) {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee one = employeeDao.selectOne(queryWrapper);
        if (one!=null){
            throw new NameException(employee.getUsername());
        }

        employee.setCreateTime(LocalDateTime.now());//
        employee.setUpdateTime(LocalDateTime.now());
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employeeDao.insert(employee);
    }

    @Override
    public Page<Employee> findPage(Page<Employee> pageInfo, LambdaQueryWrapper<Employee> queryWrapper) {
        return employeeDao.selectPage(pageInfo,queryWrapper);
    }

    @Override
    public Employee findById(Long id) {

        return employeeDao.selectById(id);
    }
}
